package com.juyu.reader.pc.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.juyu.reader.pc.common.Constants;
import com.juyu.reader.pc.common.PageDirective;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.model.BookChapter;
import com.juyu.reader.pc.model.Collection;
import com.juyu.reader.pc.model.Order;
import com.juyu.reader.pc.model.Page;
import com.juyu.reader.pc.model.Pay;
import com.juyu.reader.pc.model.PayAuto;
import com.juyu.reader.pc.model.User;
import com.juyu.reader.pc.model.Validate;
import com.juyu.reader.pc.service.BookChapterService;
import com.juyu.reader.pc.service.BookService;
import com.juyu.reader.pc.service.CollectionService;
import com.juyu.reader.pc.service.OrderService;
import com.juyu.reader.pc.service.PayAutoService;
import com.juyu.reader.pc.service.PayService;
import com.juyu.reader.pc.service.UserService;
import com.juyu.reader.pc.service.ValidateService;
import com.juyu.reader.pc.util.BigDecimalUtil;
import com.juyu.reader.pc.util.DateUtil;
import com.juyu.reader.pc.util.Md5Util;
import com.juyu.reader.pc.util.NetUtil;
import com.juyu.reader.pc.util.StringUtil;


import net.sf.json.JSONObject;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	Logger loger = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private CollectionService collectionService;
	// @Autowired
	// private CommentService commentService;
	@Autowired
	private ValidateService validateService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private PayService payService;
	@Autowired
	private BookService bookService;
	@Autowired
	private BookChapterService bookChapterService;
	@Autowired
	private PayAutoService payAutoService;
	// @Autowired
	// private RecommendService recommendService;
	// @Autowired
	// private IndexService indexService;

	/**
	 * 如果用户没有登录会先跳转到这里
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/toLogin")
	public ModelAndView toLogin(HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(Constants.SYSTEM_SESSION_USER);
		if (loginUser == null) {
			return this.packModeAndView(request, "/user/login", null, null);
		} else {
			return this.packModeAndView(request, "redirect:/home/index", null, null);
		}

	}

	@RequestMapping("/login")
	@ResponseBody
	public String login(User user, HttpServletRequest request, HttpServletResponse response) {
		String referer = request.getHeader("Referer");
		if (StringUtil.isNullOrEmpty(referer)) {
			return null;
		}
		User loginUser = new User();
		loginUser.setUserAccount(user.getUserAccount());
		loginUser.setUserPassword(Md5Util.md5Encode(user.getUserPassword()));
		List<User> userList = userService.loginUser(loginUser);

		JSONObject resultObj = new JSONObject();
		if (userList.size() == 1) {
			User resultUser = userList.get(0);
			if (resultUser.getUserStatus() == 1) {
				// 用户基本信息，存入session
				this.setSessionUser(request, resultUser);
				// 设置自动登录cookie
				// userService.setCookieToken(resultUser, request, response);
				// 查询用户收藏书籍，存入session
				Collection findCollection = new Collection();
				findCollection.setUserId(resultUser.getUserId());
				List<Collection> collectionList = collectionService.findCollection(findCollection);
				request.getSession().setAttribute(Constants.USER_COLLECTION_LIST, collectionList);
				// 查询用户自动订阅书籍，存入session
				PayAuto findPayAuto = new PayAuto();
				findPayAuto.setUserId(resultUser.getUserId());
				List<PayAuto> payAutoList = payAutoService.findPayAuto(findPayAuto);
				request.getSession().setAttribute(Constants.USER_PAY_AUTO_LIST, payAutoList);
				resultObj.put("code", 0);
				String lastUrl = (String) request.getSession().getAttribute(Constants.LAST_URL);
				if (lastUrl != null) {
					resultObj.put("url", lastUrl);
				} else {
					resultObj.put("url", request.getContextPath() + "/home/index");
				}
			} else if (resultUser.getUserStatus() == -1) {
				resultObj.put("code", -2);
				resultObj.put("message", "用户帐号被禁用！");
			} else {
				resultObj.put("code", -3);
				resultObj.put("message", "登录失败，账号状态未知错误！");
			}
		} else {
			resultObj.put("code", -1);
			resultObj.put("message", "用户名或密码错误！");
		}
		return resultObj.toString();
	}

	@RequestMapping("/toRegister")
	public ModelAndView toRegister(HttpServletRequest request) {
		return this.packModeAndView(request, "/user/register", null, null);
	}

	@RequestMapping("/register")
	@ResponseBody
	public String register(User user, HttpServletRequest request) {
		User findUser = new User();
		findUser.setUserAccount(user.getUserAccount());
		List<User> userList = userService.validateUser(findUser);
		JSONObject resultObj = new JSONObject();
		if (userList.size() >= 1) {
			resultObj.put("code", -1);
			resultObj.put("message", "账号已经存在！");
			return resultObj.toString();
		}
		Validate validate = new Validate();
		validate.setValidatePhone(user.getUserAccount());
		List<Validate> validateList = validateService.findValidate(validate);
		int registerResult;
		if (validateList.size() >= 1) {
			Validate v = validateList.get(0);
			if (v.getValidateCode().equals(user.getUserValidateCode())) {
				user.setUserPassword(Md5Util.md5Encode(user.getUserPassword()));
				user.setUserPlatform(4);// 0默认 ，1web平台 ，2ios平台 ，3android平台，4pc平台
				user.setUserType(1);// 0默认，1官方手机号注册，2微信，3qq，4微博
				user.setUserPhone(user.getUserAccount());
				String userNickCode = "";
				if (user.getUserAccount().length() >= 11) {
					userNickCode = user.getUserAccount().substring(7, 11);
				} else if (user.getUserAccount().length() >= 4) {
					userNickCode = user.getUserAccount().substring(0, 4);
				} else {

				}
				String userNicknameStr = StringUtil.createUserNickname(userNickCode);
				user.setUserNickname(userNicknameStr);
				user.setUserNo(StringUtil.createUserNo());
				user.setUserChannelNo(this.getChannelNo(request));
				registerResult = userService.insertUser(user);
			} else {
				resultObj.put("code", -3);
				resultObj.put("message", "验证码输入错误！");
				return resultObj.toString();
			}
		} else {
			resultObj.put("code", -2);
			resultObj.put("message", "验证码输入错误或已失效！");
			return resultObj.toString();
		}

		if (registerResult == 1) {
			// 注册成功后删除验证码记录
			Validate deleteValidate = new Validate();
			deleteValidate.setValidatePhone(user.getUserAccount());
			deleteValidate.setValidateCode(user.getUserValidateCode());
			validateService.deleteValidate(deleteValidate);
			// 注册成功后自动登录系统
			User loginUser = new User();
			loginUser.setUserAccount(user.getUserAccount());
			loginUser.setUserPassword(user.getUserPassword());// 注册的时候已经md5加密转换
			List<User> autoUserList = userService.loginUser(loginUser);
			if (autoUserList.size() == 1) {
				User resultUser = autoUserList.get(0);
				if (resultUser.getUserStatus() == 1) {
					this.setSessionUser(request, resultUser);
					Collection findCollection = new Collection();
					findCollection.setUserId(resultUser.getUserId());
					List<Collection> collectionList = collectionService.findCollection(findCollection);
					request.getSession().setAttribute(Constants.USER_COLLECTION_LIST, collectionList);
					PayAuto findPayAuto = new PayAuto();
					findPayAuto.setUserId(resultUser.getUserId());
					List<PayAuto> payAutoList = payAutoService.findPayAuto(findPayAuto);
					request.getSession().setAttribute(Constants.USER_PAY_AUTO_LIST, payAutoList);
					resultObj.put("code", 0);
					resultObj.put("url", request.getContextPath() + "/home/index");
				} else if (resultUser.getUserStatus() == -1) {
					resultObj.put("code", -7);
					resultObj.put("message", "自动登录失败，用户帐号被冻结！");
				} else {
					resultObj.put("code", -6);
					resultObj.put("message", "自动登录失败，账号状态未知错误！");
				}
			} else {
				resultObj.put("code", -5);
				resultObj.put("message", "自动登录失败，用户名或密码错误！");
			}
		} else {
			resultObj.put("code", -4);
			resultObj.put("message", "注册失败！");
		}
		return resultObj.toString();
	}

	 @RequestMapping("/toOauthwx")
	 public String toOauthwxRegister(User user, HttpServletRequest request) {
		 String isWeiXin = request.getParameter("isWeiXin");
		//第三方登录参数
		 String URL = "https://open.weixin.qq.com/connect/qrconnect";
		 String AppID = "wx47f86d966249ea11";
		 String AppSecret = "1a668a85946ca23a9dbf1d0a8a6e918b";
		 String scope = "snsapi_login";
		 if(isWeiXin!= null && !isWeiXin.equals("")&& !isWeiXin.equals(null) && isWeiXin.equals("1")){
			 // 公众号登录
			 AppID = "wxadcdbbf02d887960";
			 AppSecret = "88a59fdff88c98afc89537130704e93c";
			 URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
			 scope = "snsapi_userinfo";
		 }
		 // 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
		 // 公众号登录
		 // AppID:wxadcdbbf02d887960
		 // AppSecret:88a59fdff88c98afc89537130704e93c
		 //第三方登录参数
		 //AppID: wx47f86d966249ea11
		 // AppSecret:1a668a85946ca23a9dbf1d0a8a6e918b
		 String state = StringUtil.createNumberUUID();
		 String wxUrl = "redirect:"+URL+"?"
				 +"appid="+AppID
				 +"&redirect_uri=http%3a%2f%2fwww.xueerbook.com%2freaderpc%2fuser%2foauthwx?isWeiXin="+isWeiXin
				 +"&response_type=code&scope="+scope+"&state="+ state + "#wechat_redirect";
		 loger.info("发起微信登录请求：isWeiXin="+isWeiXin+"-----wxUrl="+wxUrl);
		 return wxUrl;
//	 	"redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxadcdbbf02d887960&redirect_uri=http%3a%2f%2fwww.xueerbook.com%2freaderpc%2fuser%2foauthwx&response_type=code&scope=snsapi_userinfo&state="
//	 	+ state + "#wechat_redirect";
				 
	 }
	
	@RequestMapping("/toOauthqq")
	public String toOauthqqRegister(User user, HttpServletRequest request) {
		// 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
		String state = StringUtil.createNumberUUID();
		//APP ID：101675225
		//APP Key：d47dca5d4b007fbbb4230aa139ade788
//		return "redirect:https://graph.qq.com/oauth2.0/authorize?client_id=101394518&state=" + state
//				+ "&response_type=code&redirect_uri=http%3a%2f%2fwww.juzibook.com%2fuser%2foauthqq";
		return "redirect:https://graph.qq.com/oauth2.0/authorize?client_id=101675225&state=" + state
		+ "&response_type=code&redirect_uri=http%3a%2f%2fwww.xueerbook.com%2freaderpc%2fuser%2foauthqq";
	}

	@RequestMapping("/toOauthwb")
	public String toOauthwbRegister(User user, HttpServletRequest request) {
		// 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
		String state = StringUtil.createNumberUUID();
		return "redirect:https://api.weibo.com/oauth2/authorize?client_id=3738899746&state=" + state
				+ "&redirect_uri=http://www.juzibook.com/user/oauthwb";
	}

	@RequestMapping("/oauthwx")
	public String oauthwxRegister(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					paramsMap.put(paramName, paramValue);
				}
			}
		}
		Set<Map.Entry<String, String>> set = paramsMap.entrySet();
		loger.info("oauthwx callback----------------------------->>");
		loger.info("from wx user channelNo=" + (String) request.getSession().getAttribute("channelNo"));
		for (Map.Entry<String, String> entry : set) {
			loger.info(entry.getKey() + ":" + entry.getValue());
		}
		loger.info("oauthwx callback-----------------------------<<");
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		if (!StringUtil.isNullOrEmpty(code)) {
			// 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
			if (!StringUtil.isNullOrEmpty(state)) {
				try {
					String isWeiXin = request.getParameter("isWeiXin");
					loger.info("微信请求回调：isWeiXin="+isWeiXin);
					//第三方登录参数
					 String AppID = "wx47f86d966249ea11";
					 String AppSecret = "1a668a85946ca23a9dbf1d0a8a6e918b";
					 if(isWeiXin!= null && !isWeiXin.equals("")&& !isWeiXin.equals(null) && isWeiXin.equals("1")){
						 // 公众号登录
						 AppID = "wxadcdbbf02d887960";
						 AppSecret = "88a59fdff88c98afc89537130704e93c";
					 }
					CloseableHttpClient httpclient = HttpClients.createDefault();
					String serverUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?"
							+"appid="+ AppID +"&secret="+AppSecret
							+"&code="+ code + "&grant_type=authorization_code";
					HttpGet httpGet = new HttpGet(serverUrl);
					CloseableHttpResponse closresponse = httpclient.execute(httpGet);
					HttpEntity entity = closresponse.getEntity();
					String result = EntityUtils.toString(entity, "utf-8");
					loger.info("result=" + result);
					JSONObject resultObj = JSONObject.fromObject(result);
					String accessToken = resultObj.optString("access_token", "");
					String expiresIn = resultObj.optString("expires_in", "");
					String refreshToken = resultObj.optString("refresh_token", "");//
					// token过期时使用
					String openid = resultObj.optString("openid", "");

					if (!StringUtil.isNullOrEmpty(accessToken)) {
						// 获取用户信息
						httpGet = new HttpGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken
								+ "&openid=" + openid);
						closresponse = httpclient.execute(httpGet);
						HttpEntity entity2 = closresponse.getEntity();
						String userInfoResult = EntityUtils.toString(entity2, "utf-8");
						loger.info("userInfoResult=" + userInfoResult);
						JSONObject userInfoObj = JSONObject.fromObject(userInfoResult);
						String nickname = userInfoObj.optString("nickname", "");
						String imageUrl = userInfoObj.optString("headimgurl", "");
						String unionid = userInfoObj.optString("unionid", "");
						// 检查用户是否已经注册
						User updateUser = new User();
						updateUser.setUserOpenId(openid);
						updateUser.setUserUnionId(unionid);
						updateUser.setUserType(2);
						updateUser.setUserStatus(1);
						updateUser.setUserPlatform(1);
						updateUser.setUserAccessToken(accessToken);
						updateUser.setUserChannelNo((String) request.getSession().getAttribute("channelNo"));

						if (!StringUtil.isNullOrEmpty(nickname)) {
							updateUser.setUserNickname(nickname);
						} else {
							updateUser.setUserNickname(StringUtil.createUserNicknameWX());
						}
						if (!StringUtil.isNullOrEmpty(imageUrl)) {
							updateUser.setUserImageType(1);
							updateUser.setUserImage(imageUrl);
						}
						int opResult = 0;
						// 先查看是否已经存在unionid
						List<User> userList = userService.validateUserByUnionId(updateUser);
						loger.info("wx unionid size=" + userList.size());
						// List<User> userList =
						// userService.validateUserByOpenId(updateUser);//账号通用，不再使用openid
						if (userList.size() >= 1) {
//							 opResult =
//							 userService.updateUserOauth(updateUser);
							loger.info("登录用户：unionid:"+updateUser.getUserUnionId());
							// 如果已经存在unionid，则判断是否使用统一账号以及openid是否一致，如果不一致则说明是另一个应用的openid，更新user_relation_id，等待手动关联
//							if (StringUtil.isNullOrEmpty(userList.get(0).getUserRelationId())
//									&& !openid.equals(userList.get(0).getUserOpenId())
//									&& userList.get(0).getUserIsUnion() == 0) {
//
//								// 更新用户userRelationId
//								updateUser.setUserRelationId(userList.get(0).getUserOpenId());
//								userService.updateUserRelationId(updateUser);
//							}
							return this.toAutoLoginByOauth(request, response, updateUser, 1, model);
						} else {
							// 如果unionid不存在，先判断openid是否存在，如果存在，则更新该用户的unionid，否则是新用户执行注册机制
							userList = userService.validateUserByOpenId(updateUser);
							if (userList.size() >= 1) {
								loger.info("登录用户：open_id:"+updateUser.getUserOpenId());
//								opResult = userService.updateUserUnionId(updateUser);
								opResult = 1;
							} else {
								updateUser.setUserNo(StringUtil.createUserNo());
								updateUser.setUserIsUnion(1);
								opResult = userService.insertUser(updateUser);
								loger.info("注册用户：open_id:"+updateUser.getUserOpenId());
							}
						}
						if (opResult == 1) {
							return this.toAutoLoginByOauth(request, response, updateUser, 2, model);
						}
					}
					EntityUtils.consume(entity);
				} catch (Exception e) {
					loger.info(e.toString());
				}
			} else {

			}
		}
		return this.packStringView(request, "/book/error", "第三方微信登录失败！", model);
	}

	@RequestMapping("/oauthqq")
	public String oauthqqRegister(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					paramsMap.put(paramName, paramValue);
				}
			}
		}
		Set<Map.Entry<String, String>> set = paramsMap.entrySet();
		loger.info("oauthqq callback----------------------------->>");
		for (Map.Entry<String, String> entry : set) {
			loger.info(entry.getKey() + ":" + entry.getValue());
		}
		loger.info("oauthqq callback-----------------------------<<");
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		if (!StringUtil.isNullOrEmpty(code)) {
			// 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
			if (!StringUtil.isNullOrEmpty(state)) {
				try {
					CloseableHttpClient httpclient = HttpClients.createDefault();
					String serverUrl = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=101675225&client_secret=d47dca5d4b007fbbb4230aa139ade788&code="
							+ code + "&redirect_uri=http%3a%2f%2fwww.xueerbook.com%2freaderpc%2fuser%2foauthqq";
					HttpGet httpGet = new HttpGet(serverUrl);
					CloseableHttpResponse closresponse = httpclient.execute(httpGet);
					HttpEntity entity = closresponse.getEntity();
					String result = EntityUtils.toString(entity, "utf-8");
					loger.info("result=" + result);
					Map<String, String> resultMap = StringUtil.parseFormDataPatternReport(result);
					String accessToken = resultMap.get("access_token");
					String expiresIn = resultMap.get("expires_in");
					String refreshToken = resultMap.get("refresh_token");// token过期时使用
					if (!StringUtil.isNullOrEmpty(accessToken)) {
						// 获取用户openid
						httpGet = new HttpGet(
								"https://graph.qq.com/oauth2.0/me?access_token=" + accessToken + "&unionid=1");// unionid账号通用唯一标识（wap和app应用共用unionid，需要联系客服申请打通）
						closresponse = httpclient.execute(httpGet);
						HttpEntity entity2 = closresponse.getEntity();
						String userTokenResult = EntityUtils.toString(entity2, "utf-8");
						loger.info("userTokenResult=" + userTokenResult);
						userTokenResult = userTokenResult.replace("callback( ", "");
						userTokenResult = userTokenResult.replace(" );", "");// 过滤其它字符
						JSONObject userTokenObj = JSONObject.fromObject(userTokenResult);
						String openid = userTokenObj.optString("openid", "");
						String unionid = userTokenObj.optString("unionid", "");// unionid账号通用唯一标识
						// 获取用户信息
						httpGet = new HttpGet("https://graph.qq.com/user/get_user_info?access_token=" + accessToken
								+ "&oauth_consumer_key=101675225&openid=" + openid);
						closresponse = httpclient.execute(httpGet);
						HttpEntity entity3 = closresponse.getEntity();
						String userInfoResult = EntityUtils.toString(entity3, "utf-8");
						loger.info("userInfoResult=" + userInfoResult);
						loger.info("qq unionid=" + unionid);
						JSONObject userInfoObj = JSONObject.fromObject(userInfoResult);
						String nickname = userInfoObj.optString("nickname", "");
						String imageUrl = userInfoObj.optString("figureurl_qq_1", "");
						// 检查用户是否已经注册
						User updateUser = new User();
						updateUser.setUserOpenId(openid);
						updateUser.setUserUnionId(unionid);
						updateUser.setUserType(3);
						updateUser.setUserStatus(1);
						updateUser.setUserPlatform(4);
						updateUser.setUserAccessToken(accessToken);
						updateUser.setUserChannelNo(this.getChannelNo(request));

						if (!StringUtil.isNullOrEmpty(nickname)) {
							updateUser.setUserNickname(nickname);
						} else {
							updateUser.setUserNickname(StringUtil.createUserNicknameQQ());
						}
						if (!StringUtil.isNullOrEmpty(imageUrl)) {
							updateUser.setUserImage(imageUrl);
							updateUser.setUserImageType(1);// 用户头像类型：默认0，0官方图片上传，1第三方平台图片链接
						}
						// 检查用户是否已经注册
						int opResult = 0;
						List<User> userList = userService.validateUserByUnionId(updateUser);
						if (userList.size() >= 1) {
							opResult = 1;
						} else {
							updateUser.setUserNo(StringUtil.createUserNo());
							updateUser.setUserIsUnion(1);
							opResult = userService.insertUser(updateUser);
						}
						if (opResult == 1) {
							return this.toAutoLoginByOauth(request, response, updateUser, 2, model);
						}
					}
					EntityUtils.consume(entity);
				} catch (Exception e) {
					loger.info(e.toString());
				}
			} else {

			}
		}
		return this.packStringView(request, "/book/error", "第三方qq登录失败！", model);
	}

	@RequestMapping("/oauthwb")
	public String oauthwbRegister(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();

			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() != 0) {
					paramsMap.put(paramName, paramValue);
				}
			}
		}
		Set<Map.Entry<String, String>> set = paramsMap.entrySet();
		loger.info("oauthwb callback----------------------------->>");
		for (Map.Entry<String, String> entry : set) {
			loger.info(entry.getKey() + ":" + entry.getValue());
		}
		loger.info("oauthwb callback-----------------------------<<");
		String code = request.getParameter("code");
		String state = request.getParameter("state");
		if (!StringUtil.isNullOrEmpty(code)) {
			// 防止CSRF攻击（将state uuid放入redis，服务端匹配验证，目前暂时不验证）
			if (!StringUtil.isNullOrEmpty(state)) {
				try {
					CloseableHttpClient httpclient = HttpClients.createDefault();
					HttpPost httpPost = new HttpPost("https://api.weibo.com/oauth2/access_token");

					List<NameValuePair> nvps = new ArrayList<NameValuePair>();
					nvps.add(new BasicNameValuePair("client_id", "3738899746"));
					nvps.add(new BasicNameValuePair("client_secret", "2e3aa63b829ccc7157456b9f14587fad"));
					nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
					nvps.add(new BasicNameValuePair("code", code));
					nvps.add(new BasicNameValuePair("redirect_uri", "http://www.juzibook.com/user/oauthwb"));
					httpPost.setEntity(new UrlEncodedFormEntity(nvps));
					CloseableHttpResponse closresponse = httpclient.execute(httpPost);
					HttpEntity entity = closresponse.getEntity();
					String result = EntityUtils.toString(entity, "utf-8");
					loger.info("result=" + result);
					JSONObject resultObj = JSONObject.fromObject(result);
					String accessToken = resultObj.optString("access_token", "");
					int expiresIn = resultObj.optInt("expires_in", 0);
					String uid = resultObj.optString("uid", "");
					if (!StringUtil.isNullOrEmpty(accessToken)) {
						// 获取用户信息
						HttpGet httpGet = new HttpGet(
								"https://api.weibo.com/2/users/show.json?access_token=" + accessToken + "&uid=" + uid);
						closresponse = httpclient.execute(httpGet);
						HttpEntity entity2 = closresponse.getEntity();
						String userInfoResult = EntityUtils.toString(entity2, "utf-8");
						loger.info("userInfoResult=" + userInfoResult);
						JSONObject userObj = JSONObject.fromObject(userInfoResult);
						String nickname = userObj.optString("screen_name", "");
						String imageUrl = userObj.optString("profile_image_url", "");
						// 检查用户是否已经注册
						User updateUser = new User();
						updateUser.setUserOpenId(uid);
						updateUser.setUserType(4);
						updateUser.setUserStatus(1);
						updateUser.setUserPlatform(1);
						updateUser.setUserAccessToken(accessToken);
						updateUser.setUserChannelNo(this.getChannelNo(request));

						if (!StringUtil.isNullOrEmpty(nickname)) {
							updateUser.setUserNickname(nickname);
						} else {
							updateUser.setUserNickname(StringUtil.createUserNicknameWB());
						}
						if (!StringUtil.isNullOrEmpty(imageUrl)) {
							updateUser.setUserImage(imageUrl);
							updateUser.setUserImageType(1);// 用户头像类型：默认0，0官方图片上传，1第三方平台图片链接
						}
						int opResult = 0;
						List<User> userList = userService.validateUserByOpenId(updateUser);
						if (userList.size() >= 1) {
							opResult = 1;
						} else {
							updateUser.setUserNo(StringUtil.createUserNo());
							opResult = userService.insertUser(updateUser);
						}
						if (opResult == 1) {
							return this.toAutoLoginByOauth(request, response, updateUser, 2, model);
						}
					}
					EntityUtils.consume(entity);
				} catch (Exception e) {
					loger.info(e.toString());
				}
			} else {

			}
		}
		return this.packStringView(request, "/book/error", "第三方微博登录失败！", model);

	}

	private String toAutoLoginByOauth(HttpServletRequest request, HttpServletResponse response, User openUser, int type,
			Model model) {
		// 第三方登录成功后自动登录本系统
		List<User> autoUserList = new ArrayList<User>();
		if (type == 1) {
			autoUserList = userService.loginUserByUnionId(openUser);
		} else if (type == 2) {
			autoUserList = userService.loginUserByOpenId(openUser);
		}
		loger.info("第三方自动登录：size="+autoUserList.size());
		if (autoUserList.size() == 1) {
			User resultUser = autoUserList.get(0);
			if (resultUser.getUserStatus() == 1) {
				// 设置session
				this.setSessionUser(request, resultUser);
				Collection findCollection = new Collection();
				findCollection.setUserId(resultUser.getUserId());
				List<Collection> collectionList = collectionService.findCollection(findCollection);
				request.getSession().setAttribute(Constants.USER_COLLECTION_LIST, collectionList);
				PayAuto findPayAuto = new PayAuto();
				findPayAuto.setUserId(resultUser.getUserId());
				List<PayAuto> payAutoList = payAutoService.findPayAuto(findPayAuto);
				request.getSession().setAttribute(Constants.USER_PAY_AUTO_LIST, payAutoList);

				String lastUrl = (String) request.getSession().getAttribute(Constants.LAST_URL);
				loger.info("qq+wb=lasturl=" + lastUrl);
				if (lastUrl != null) {
					return this.packStringView(request, "/user/info", null, model);
				} else {
					return this.packStringView(request, "/user/info", null, model);

				}
			} else {
				return this.packStringView(request, "/book/error", "登录失败，用户帐号异常！", model);
			}
		} else {
			return this.packStringView(request, "/book/error", "登录失败，用户帐号不存在！", model);
		}

	}

	@RequestMapping("/sendSMS")
	@Transactional
	@ResponseBody
	public String sendSMS(User user, HttpServletRequest request) {
		// 如果不是从注册页面进入发生验证码
		String referer = request.getHeader("Referer");
		if (StringUtil.isNullOrEmpty(referer)) {
			return "error:-1";
		} else {
			if (!referer.contains("user/toRegister")) {
				return "error:-2";
			}
		}
		if (StringUtil.isNullOrEmpty(user.getUserAccount())) {
			return "error:-3";
		}
		User findUser = new User();
		findUser.setUserAccount(user.getUserAccount());
		List<User> userList = userService.validateUser(findUser);
		JSONObject resultObj = new JSONObject();
		if (userList.size() >= 1) {
			resultObj.put("code", -1);
			resultObj.put("message", "账号已经存在！");
			return resultObj.toString();
		}
		Validate validate = new Validate();
		validate.setValidateIP(NetUtil.getIpAddress(request));
		validate.setBeginDate(DateUtil.getDayBegin(new Date()));
		validate.setEndDate(DateUtil.getDayEnd(new Date()));
		validate.setValidatePhone(user.getUserAccount());
		validate.setValidateCode(StringUtil.createValidateCode());
		validate.setValidateContent("您此次申请手机注册的验证码：" + validate.getValidateCode() + "如非本人操作，请忽略。");
		validate.setValidateDate(Calendar.getInstance().getTime());
		Validate validateResult = new Validate();
		List<Validate> validateList = validateService.findValidateByDate(validate);
		// 验证码发送达到上限（一天上限数是200）
		if (validateList.size() >= 200) {
			resultObj.put("code", -3);
			resultObj.put("message", "证码发送已达上限，请稍后重试！（-200）");
			return resultObj.toString();
		}
		validateList = validateService.findValidateByIP(validate);
		// 验证码发送达到上限（一天上限数是5）
		if (validateList.size() >= 5) {
			resultObj.put("code", -5);
			resultObj.put("message", "证码发送已达上限，请稍后重试！（-5）");
			return resultObj.toString();
		}
		validateList = validateService.findValidate(validate);
		// 验证码发送达到上限
		if (validateList.size() >= 3) {
			resultObj.put("code", -3);
			resultObj.put("message", "该手机验证码发送已达上限，请稍后重试！");
			return resultObj.toString();
		}
		if (validateList.size() >= 1) {
			Validate v = validateList.get(0);
			long nowTimes = Calendar.getInstance().getTime().getTime() / 1000;
			long validTimes = v.getValidateDate().getTime() / 1000;
			if (nowTimes - validTimes > 60) {
				validateResult = validateService.sendValidateCode(validate);
			} else {
				resultObj.put("code", -4);
				resultObj.put("message", "请勿频繁发送短信验证，稍后重试！");
				return resultObj.toString();
			}
		} else {
			validateResult = validateService.sendValidateCode(validate);
		}

		if (validateResult.isSendSuccess()) {
			validateService.insertValidate(validate);
			validate.setValidateResponse(validateResult.getValidateResponse());
			validateService.insertValidateRecord(validate);
			resultObj.put("code", 0);
			resultObj.put("message", "验证码发送成功，手机请注意查收！");
		} else {
			resultObj.put("code", -2);
			resultObj.put("message", "验证码发送失败！");
		}
		return resultObj.toString();
	}

	@RequestMapping("/sendForgetSMS")
	@Transactional
	@ResponseBody
	public String sendForgetSMS(User user, HttpServletRequest request) {
		// 如果不是从注册页面进入发生验证码
		String referer = request.getHeader("Referer");
		if (StringUtil.isNullOrEmpty(referer)) {
			return "error:-1";
		} else {
			if (!referer.contains("user/pwdForget")) {
				return "error:-2";
			}
		}
		if (StringUtil.isNullOrEmpty(user.getUserAccount())) {
			return "error:-3";
		}
		User findUser = new User();
		findUser.setUserAccount(user.getUserAccount());
		List<User> userList = userService.validateUser(findUser);
		JSONObject resultObj = new JSONObject();
		if (userList.size() == 0) {
			resultObj.put("code", -1);
			resultObj.put("message", "账号不存在！");
			return resultObj.toString();
		}
		Validate validate = new Validate();
		validate.setValidateIP(NetUtil.getIpAddress(request));
		validate.setBeginDate(DateUtil.getDayBegin(new Date()));
		validate.setEndDate(DateUtil.getDayEnd(new Date()));
		validate.setValidatePhone(user.getUserAccount());
		validate.setValidateCode(StringUtil.createValidateCode());
		validate.setValidateContent("您此次申请重置密码的验证码：" + validate.getValidateCode() + "如非本人操作，请忽略。");
		validate.setValidateDate(Calendar.getInstance().getTime());
		Validate validateResult = new Validate();
		List<Validate> validateList = validateService.findValidateByDate(validate);
		// 验证码发送达到上限（一天上限数是200）
		if (validateList.size() >= 200) {
			resultObj.put("code", -3);
			resultObj.put("message", "证码发送已达上限，请稍后重试！（-200）");
			return resultObj.toString();
		}
		validateList = validateService.findValidateByIP(validate);
		// 验证码发送达到上限（一天上限数是5）
		if (validateList.size() >= 5) {
			resultObj.put("code", -5);
			resultObj.put("message", "证码发送已达上限，请稍后重试！（-5）");
			return resultObj.toString();
		}
		validateList = validateService.findValidate(validate);
		// 验证码发送达到上限
		if (validateList.size() >= 3) {
			resultObj.put("code", -3);
			resultObj.put("message", "该手机验证码发送已达上限，请稍后重试！");
			return resultObj.toString();
		}
		if (validateList.size() >= 1) {
			Validate v = validateList.get(0);
			long nowTimes = Calendar.getInstance().getTime().getTime() / 1000;
			long validTimes = v.getValidateDate().getTime() / 1000;
			if (nowTimes - validTimes > 60) {
				validateResult = validateService.sendValidateCode(validate);
			} else {
				resultObj.put("code", -4);
				resultObj.put("message", "请勿频繁发送短信验证，稍后重试！");
				return resultObj.toString();
			}
		} else {
			validateResult = validateService.sendValidateCode(validate);
		}

		if (validateResult.isSendSuccess()) {
			validateService.insertValidate(validate);
			validate.setValidateResponse(validateResult.getValidateResponse());
			validateService.insertValidateRecord(validate);
			resultObj.put("code", 0);
			resultObj.put("message", "验证码发送成功，手机请注意查收！");
		} else {
			resultObj.put("code", -2);
			resultObj.put("message", "验证码发送失败！");
		}
		return resultObj.toString();
	}

	@RequestMapping("/protocol")
	@ResponseBody
	public ModelAndView protocol(User user, HttpServletRequest request) {
		return this.packModeAndView(request, "/user/protocol", null, null);
	}

	@RequestMapping("/info")
	public ModelAndView userInfo(HttpServletRequest request) {
		User loginUser = this.getSessionUser(request);
		List<User> userList = userService.findUserById(loginUser.getUserId());
		if (userList.size() == 1) {
			this.setSessionUser(request, userList.get(0));

		}
		long to = Calendar.getInstance().getTime().getTime();
		long from = loginUser.getUserDate().getTime();
		long userDay = (to - from) / (1000 * 60 * 60 * 24);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		attrMap.put("userDay", userDay);
		return this.packModeAndView(request, "/user/info", null, attrMap);
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		request.getSession().removeAttribute(Constants.SYSTEM_SESSION_USER);
		request.getSession().removeAttribute(Constants.USER_COLLECTION_LIST);
		request.getSession().removeAttribute(Constants.USER_PAY_AUTO_LIST);
		request.getSession().removeAttribute(Constants.LAST_URL);
		// userService.delCookieToken(null, request, response);
		return "redirect:/home/index";
	}

	@RequestMapping("/collection")
	public ModelAndView collectionList(HttpServletRequest request, Page page) {
		User sessionUser = this.getSessionUser(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Collection findCollection = new Collection();
		findCollection.setUserId(sessionUser.getUserId());
		findCollection.setPageNo(page.getPageNo());
		findCollection.setLimit(page.getLimit());
		List<Collection> collectionList = collectionService.findCollection(findCollection);
		int count = collectionService.countCollection(findCollection);
		attrMap.put("collectionList", collectionList);
		attrMap.put("sourceUrl", Constants.SOURCE_URL);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request, page.getLimit()));
		return this.packModeAndView(request, "/user/collection", null, attrMap);
	}

	@RequestMapping("/collectionDel")
	public String collectionDel(HttpServletRequest request, Collection collection) {
		User sessionUser = this.getSessionUser(request);
		collection.setUserId(sessionUser.getUserId());
		int deleteResult = collectionService.deleteCollection(collection);
		if (deleteResult == 1) {
			Collection findCollection = new Collection();
			findCollection.setUserId(sessionUser.getUserId());
			List<Collection> collectionList = collectionService.findCollection(findCollection);
			request.getSession().setAttribute(Constants.USER_COLLECTION_LIST, collectionList);
		}
		return "redirect:/user/collection";
	}

	@RequestMapping("/collectionAdd")
	public String collectionAdd(HttpServletRequest request, Collection collection, Model model) {
		if (collection.getBookId() == 0) {
			return this.packStringView(request, "/book/error", "非法请求操作！", model);
		}
		User sessionUser = this.getSessionUser(request);
		collection.setUserId(sessionUser.getUserId());
		int insertResult = collectionService.insertCollection(collection);
		if (insertResult == 1) {
			Collection findCollection = new Collection();
			findCollection.setUserId(sessionUser.getUserId());
			List<Collection> collectionList = collectionService.findCollection(findCollection);
			request.getSession().setAttribute(Constants.USER_COLLECTION_LIST, collectionList);
		}
		return "redirect:/book/bookInfo?bookId=" + collection.getBookId();
	}

	// @RequestMapping("/commentAdd")
	// public ModelAndView commentAdd(HttpServletRequest request, Comment
	// comment) {
	// Map<String, Object> attrMap = new HashMap<String, Object>();
	// if (comment.getBookId() == 0) {
	// return this.packModeAndView(request, "/book/error", "非法请求操作！", null);
	// }
	// Comment findComment = new Comment();
	// findComment.setBookId(comment.getBookId());
	// findComment.setLimit(10);
	// List<Comment> commentList = commentService.findComment(findComment);
	// int commentCount = commentService.countComment(findComment);
	// attrMap.put("commentList", commentList);
	// attrMap.put("commentCount", commentCount);
	// attrMap.put("comment", comment);
	// return this.packModeAndView(request, "/book/commentAdd", null, attrMap);
	// }
	//
	// @RequestMapping("/commentSave")
	// public String commentSave(HttpServletRequest request, Comment comment) {
	// User loginUser = (User)
	// request.getSession().getAttribute(Configure.systemSessionUser);
	// Comment insertComment = new Comment();
	// insertComment.setUserId(loginUser.getUserId());
	// insertComment.setBookId(comment.getBookId());
	// insertComment.setCommentContent(comment.getCommentContent());
	// commentService.insertComment(insertComment);
	// return "redirect:/home/bookInfo?bookId=" + comment.getBookId();
	// }

	@RequestMapping("/rechargeRecord")
	public ModelAndView rechargeRecord(HttpServletRequest request, Page page) {
		User sessionUser = this.getSessionUser(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Order findOrder = new Order();
		findOrder.setUserId(sessionUser.getUserId());
		findOrder.setLimit(page.getLimit());
		findOrder.setPageNo(page.getPageNo());
		List<Order> orderList = orderService.findOrder(findOrder);
		int count = orderService.countOrder(findOrder);
		attrMap.put("orderList", orderList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request, page.getLimit()));
		return this.packModeAndView(request, "/user/rechargeRecord", null, attrMap);
	}

	@RequestMapping("/consumeRecord")
	public ModelAndView consumeRecord(HttpServletRequest request, Page page) {
		User sessionUser = this.getSessionUser(request);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		Pay findPay = new Pay();
		findPay.setUserId(sessionUser.getUserId());
		findPay.setLimit(page.getLimit());
		findPay.setPageNo(page.getPageNo());
		List<Pay> payList = payService.findPay(findPay);
		int count = payService.countPay(findPay);
		attrMap.put("payList", payList);
		attrMap.put("recordCount", count);
		attrMap.put("page", page);
		attrMap.put("pageftl", new PageDirective(request, page.getLimit()));
		return this.packModeAndView(request, "/user/consumeRecord", null, attrMap);
	}

	@RequestMapping("/pwdEdit")
	public ModelAndView userPasswordEdit(HttpServletRequest request) {
		User loginUser = this.getSessionUser(request);
		List<User> userList = userService.findUserById(loginUser.getUserId());
		if (userList.size() == 1) {
			this.setSessionUser(request, userList.get(0));
		}
		return this.packModeAndView(request, "/user/pwdEdit", null, null);
	}

	@RequestMapping("/pwdSave")
	public ModelAndView userPasswordSave(User user, HttpServletRequest request) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		if (StringUtil.isNullOrEmpty(user.getUserOldPassword()) || StringUtil.isNullOrEmpty(user.getUserPassword())) {
			return this.packModeAndView(request, "/user/pwdEdit", "请将旧密码和新密码填写完整！", attrMap);
		}
		User loginUser = this.getSessionUser(request);
		// 默认0，1都是官方注册用户
		if (loginUser.getUserType() > 1 || loginUser.getUserPassword() == null) {
			return this.packModeAndView(request, "/common/error", "您是通过第三方账号登录，不能在本系统重置密码！", attrMap);
		}
		if (!loginUser.getUserPassword().equals(Md5Util.md5Encode(user.getUserOldPassword()))) {
			return this.packModeAndView(request, "/user/pwdEdit", "原始密码错误！", attrMap);
		}
		User updateUser = new User();
		updateUser.setUserPassword(Md5Util.md5Encode(user.getUserPassword()));
		updateUser.setUserId(loginUser.getUserId());
		int updateResult = userService.updateUserPassword(updateUser);
		if (updateResult == 1) {
			loginUser.setUserPassword(Md5Util.md5Encode(user.getUserPassword()));
			return this.packModeAndView(request, "redirect:/user/info", null, null);
		} else {
			return this.packModeAndView(request, "/user/pwdEdit", "密码设置失败！", null);
		}

	}

	// /**
	// * 用户打赏
	// *
	// * @param request
	// * @param book
	// * @return
	// */
	// @RequestMapping("/userReward")
	// public ModelAndView userReward(HttpServletRequest request, Book book) {
	// Map<String, Object> attrMap = new HashMap<String, Object>();
	// User loginUser = (User)
	// request.getSession().getAttribute(Configure.systemSessionUser);
	// User findUser = new User();
	// findUser.setUserId(loginUser.getUserId());
	// List<User> userList = userService.findUser(findUser);
	// if (userList.size() == 1) {
	// if (book.getBookId() == 0) {
	// return this.packModeAndView(request, "/book/error", "非法操作！", attrMap);
	// }
	// User outUser = userList.get(0);
	// attrMap.put("user", outUser);
	// Book findBook = new Book();
	// findBook.setBookId(book.getBookId());
	// List<Book> bookList = bookService.findBook(findBook);
	// if (bookList.size() == 1) {
	// attrMap.put("book", bookList.get(0));
	// }
	// Pay findPay = new Pay();
	// findPay.setBookId(book.getBookId());
	// findPay.setPayType(2);
	// List<Pay> payList = payService.findPay(findPay);
	// attrMap.put("payList", payList);
	// return this.packModeAndView(request, "/user/reward", null, attrMap);
	// } else {
	// return this.packModeAndView(request, "/book/error", "用户不存在！", attrMap);
	// }
	// }
	//
	// @RequestMapping("/userRewardSave")
	// public ModelAndView userRewardSave(HttpServletRequest request, Pay pay) {
	// Map<String, Object> attrMap = new HashMap<String, Object>();
	// User sessionUser = (User)
	// request.getSession().getAttribute(Configure.systemSessionUser);
	// User findUser = new User();
	// findUser.setUserId(sessionUser.getUserId());
	// List<User> userList = userService.findUser(findUser);
	// if (pay.getPayAmount() <= 0) {
	// return this.packModeAndView(request, "/book/error", "非法操作！", attrMap);
	// }
	// if (userList.size() == 1) {
	// if (pay.getBookId() == 0 || pay.getPayAmount() == 0) {
	// return this.packModeAndView(request, "/book/error", "非法操作！", attrMap);
	// }
	// User outUser = userList.get(0);
	// int needGold = (int) (pay.getPayAmount() * 100);
	// // 余额不足
	// if (outUser.getUserGold() < needGold) {
	// return this.packModeAndView(request, "redirect:/recharge/index", null,
	// attrMap);
	// }
	// attrMap.put("user", outUser);
	// Pay insertPay = new Pay();
	// insertPay.setAuthorId(pay.getAuthorId());
	// insertPay.setBookId(pay.getBookId());
	// insertPay.setChapterId(pay.getChapterId());
	// insertPay.setUserId(outUser.getUserId());
	// insertPay.setPayAmount(pay.getPayAmount());
	// insertPay.setPayContent("打赏书籍（" + pay.getBookName() + "）" + "作者：" +
	// pay.getBookAuthorNickname());
	// insertPay.setPayType(2);
	// int insertResult = payService.insertPay(insertPay);
	// if (insertResult == 1) {
	// // 扣除用户书币
	// userService.updateUserPayGold(insertPay);
	// sessionUser.setUserGold(sessionUser.getUserGold() - needGold);
	// } else {
	// return this.packModeAndView(request, "/book/error", "打赏失败！", attrMap);
	// }
	// Pay findPay = new Pay();
	// findPay.setBookId(pay.getBookId());
	// findPay.setPayType(2);
	// List<Pay> payList = payService.findPay(findPay);
	// attrMap.put("payList", payList);
	// return this.packModeAndView(request, "redirect:/user/userReward?bookId="
	// + pay.getBookId(), null, attrMap);
	// } else {
	// return this.packModeAndView(request, "/book/error", "用户不存在！", attrMap);
	// }
	// }
	//
	// /**
	// * 用户推荐
	// *
	// * @param request
	// * @param recommend
	// * @return
	// */
	// @RequestMapping("/recommend")
	// public String userRecommend(HttpServletRequest request, Recommend
	// recommend, Model model) {
	//
	// if (recommend.getBookId() == 0) {
	// return this.packStringView(request, "/book/error", "非法请求操作！", model);
	// }
	// User sessionUser = (User)
	// request.getSession().getAttribute(Configure.systemSessionUser);
	// // 当天是否已经推荐过该书籍
	// Recommend findRecommend = new Recommend();
	// findRecommend.setUserId(sessionUser.getUserId());
	// findRecommend.setBookId(recommend.getBookId());
	// findRecommend.setBeginDate(DateUtil.getDayBegin(new Date()));
	// findRecommend.setEndDate(DateUtil.getDayEnd(new Date()));
	// List<Recommend> recommendList =
	// recommendService.findRecommend(findRecommend);
	// if (recommendList.size() >= 1) {
	// model.addAttribute("recommend", 1);
	// return "redirect:/home/bookInfo?bookId=" + recommend.getBookId();
	// }
	//
	// recommend.setUserId(sessionUser.getUserId());
	// recommend.setUserIp(NetUtil.getIpAddress(request));
	// recommendService.insertRecommend(recommend);
	// Book updateBook = new Book();
	// updateBook.setBookId(recommend.getBookId());
	// bookService.updateBookRecommend(updateBook);
	// model.addAttribute("recommend", 1);
	// return "redirect:/home/bookInfo?bookId=" + recommend.getBookId();
	//
	// }
	//
	/**
	 * 用户付费购买章节
	 *
	 * @param request
	 * @param book
	 * @return
	 */
	@RequestMapping("/payChapter")
	public String userPayChapter(HttpServletRequest request, BookChapter bookChapter, Model model) {
		User sessionUser = this.getSessionUser(request);
		if (bookChapter.getBookId() == 0 || bookChapter.getChapterId() == 0) {
			return this.packStringView(request, "/book/error", "非法操作，参数不存在！", model);
		}
		List<Book> bookList = bookService.findBookById(bookChapter.getBookId());
		if (bookList.size() != 1) {
			return this.packStringView(request, "/book/error", "非法操作，该书籍不存在！", model);
		} else {
			model.addAttribute("book", bookList.get(0));
		}

		// 查看用户是否已经购买该章节
		Pay findPay = new Pay();
		findPay.setUserId(sessionUser.getUserId());
		findPay.setBookId(bookChapter.getBookId());
		findPay.setChapterId(bookChapter.getChapterId());
		findPay.setPayType(1);// 0默认，1阅读消费，2打赏消费，3特价全本
		List<Pay> payList = payService.findPayByValidate(findPay);
		if (payList.size() >= 1) {
			return this
					.packStringView(request,
							"redirect:/book/chapterContent?bookId=" + bookChapter.getBookId() + "&chapterId="
									+ bookChapter.getChapterId() + "&bookAuthorId=" + bookChapter.getAuthorId(),
							null, model);
		} else {
			// 查看是否已经自动订阅
			List<PayAuto> payAutoList = (List<PayAuto>) request.getSession().getAttribute(Constants.USER_PAY_AUTO_LIST);
			boolean isPayAuto = false;
			if (payAutoList != null) {
				for (PayAuto p : payAutoList) {
					if (p.getBookId() == bookChapter.getBookId()) {
						isPayAuto = true;
						break;
					}
				}
			}
			model.addAttribute("isPayAuto", isPayAuto);
			List<BookChapter> bookChapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());
			if (bookChapterList.size() == 1) {
				BookChapter outChpater = bookChapterList.get(0);
				// chapterFree章节付费：0默认，1免费，2付费
				// 如果章节是付费 且 章节金额大于0
				if (outChpater.getChapterFree() == 2 && outChpater.getChapterAmount() > 0) {
					if (outChpater.getChapterContent().length() > 50) {
						outChpater.setChapterContent(outChpater.getChapterContent().substring(0, 50));
					}
					model.addAttribute("chapter", outChpater);
					// 如果用户已经设置自动订阅功能，这里执行订阅
					if (isPayAuto) {
						return this.payChapterConfirm(request, bookChapter, model);
					}
					return this.packStringView(request, "/user/payChapter", "阅读该章节需付费！", model);
				} else {
					return this.packStringView(request, "/book/error", "该章节设置付费错误，请联系客服！", model);
				}

			} else {
				return this.packStringView(request, "/book/error", "非法操作，该章节不存在！", model);
			}

		}

	}

	/**
	 * 用户在章节详细页点击“订阅该章节”按钮 购买章节
	 * 
	 * @param request
	 * @param book
	 * @return
	 */
	@RequestMapping("/payChapterConfirm")
	public String payChapterConfirm(HttpServletRequest request, BookChapter bookChapter, Model model) {
		User sessionUser = this.getSessionUser(request);
		if (bookChapter.getBookId() == 0 || bookChapter.getChapterId() == 0) {
			return this.packStringView(request, "/book/error", "非法操作，参数不存在！", model);
		}
		List<Book> bookList = bookService.findBookById(bookChapter.getBookId());
		Book outBook = null;
		if (bookList.size() != 1) {
			return this.packStringView(request, "/book/error", "非法操作，该书籍不存在！", model);
		} else {
			outBook = bookList.get(0);
		}

		List<BookChapter> bookChapterList = bookChapterService.findBookChapterById(bookChapter.getChapterId());
		if (bookChapterList.size() == 1) {
			BookChapter outChapter = bookChapterList.get(0);
			// chapterFree章节付费：0默认，1免费，2付费
			// 如果章节是付费 且 章节金额大于0
			if (outChapter.getChapterFree() == 2 && outChapter.getChapterAmount() > 0) {
				double needAmount = 0;
				int needGold = 0;
				// 判断用户余额是否充足
				List<User> userList = userService.findUserById(sessionUser.getUserId());
				if (userList.size() == 1) {
					User loginUser = userList.get(0);
					// 查看是否是半价
					needGold = (int) (outChapter.getChapterAmount() * 100);
					needAmount = outChapter.getChapterAmount();
					// 0默认，1免费，2付费，3半价，4特价全本
					if (outBook.getBookFree() == 3) {
						needGold = (int) BigDecimalUtil.mul(outChapter.getChapterAmount() * 100, 0.5);
						needAmount = BigDecimalUtil.mul(outChapter.getChapterAmount(), 0.5);
					}
					if (outBook.getBookFree() == 4) {
						needGold = outBook.getBookAmount();
						needAmount = BigDecimalUtil.div(outBook.getBookAmount(), 100, 2);
					}

					if (loginUser.getUserGold() < needGold) {
						// 用户余额不足！跳转充值页面
						return this.packStringView(request, "redirect:/recharge/index", null, model);
					}
				} else {
					return this.packStringView(request, "/book/error", "用户不存在！", model);
				}
				Pay insertPay = new Pay();
				insertPay.setBookId(outChapter.getBookId());
				insertPay.setChapterId(outChapter.getChapterId());
				insertPay.setUserId(sessionUser.getUserId());
				insertPay.setAuthorId(outBook.getAuthorId());
				if (outBook.getBookFree() == 4) {
					insertPay.setPayType(3);// 0默认，1阅读消费，2打赏消费，3特价全本
					insertPay.setPayContent("特价全本购买：" + outBook.getBookName());
				} else {
					insertPay.setPayType(1);
					insertPay.setPayContent("支付章节：" + outChapter.getChapterName());
					if (outBook.getBookFree() == 3) {
						insertPay.setPayContent("支付章节：" + outChapter.getChapterName() + "（半价活动）");
					}
				}
				insertPay.setPayAmount(needAmount);
				// 付费金币控制在1-10000之间
				if (needGold > 0 && needGold <= 10000) {
					payService.insertPay(insertPay);
					User updateUser = new User();
					updateUser.setUserId(sessionUser.getUserId());
					updateUser.setUserGold(needGold);
					userService.updateUserPayGold(updateUser);
				}
				sessionUser.setUserGold(sessionUser.getUserGold() - needGold);
				return this
						.packStringView(request,
								"redirect:/book/chapterContent?bookId=" + outChapter.getBookId() + "&chapterId="
										+ outChapter.getChapterId() + "&bookAuthorId=" + outBook.getAuthorId(),
								null, model);
			} else {
				return this.packStringView(request, "/book/error", "该章节设置付费错误，请联系客服！", model);
			}

		} else {
			return this.packStringView(request, "/book/error", "非法操作，该章节不存在！", model);
		}

	}

	/**
	 * 用户自动订阅章节
	 *
	 * @param request
	 * @param payAuto
	 * @return
	 */
	@RequestMapping("/payAuto")
	public String userPayAuto(HttpServletRequest request, PayAuto payAuto, Model model) {
		if (payAuto.getBookId() == 0) {
			return this.packStringView(request, "/book/error", "非法请求操作！", model);
		}
		User sessionUser = this.getSessionUser(request);
		payAuto.setUserId(sessionUser.getUserId());

		int insertResult = payAutoService.insertPayAuto(payAuto);
		if (insertResult == 1) {
			PayAuto findPayAuto = new PayAuto();
			findPayAuto.setUserId(sessionUser.getUserId());
			List<PayAuto> payAutoList = payAutoService.findPayAuto(findPayAuto);
			request.getSession().setAttribute(Constants.USER_PAY_AUTO_LIST, payAutoList);
		}
		if (payAuto.getFromType() == 1) {
			return "redirect:/book/chapterContent?bookId=" + payAuto.getBookId() + "&chapterId="
					+ payAuto.getChapterId() + "&authorId=" + payAuto.getAuthorId();
		} else {
			return "redirect:/home/bookInfo?bookId=" + payAuto.getBookId();
		}
	}

	// @RequestMapping("/pwdForget")
	// public ModelAndView userPasswordForget(HttpServletRequest request) {
	// return this.packModeAndView(request, "/user/pwdForget", null, null);
	// }
	//
	// @RequestMapping("/pwdForgetSave")
	// @ResponseBody
	// public String userPasswordForgetSave(User user, HttpServletRequest
	// request) {
	// JSONObject resultObj = new JSONObject();
	//
	// Validate validate = new Validate();
	// validate.setValidatePhone(user.getUserAccount());
	// List<Validate> validateList = validateService.findValidate(validate);
	// int resetResult;
	// if (validateList.size() >= 1) {
	// Validate v = validateList.get(0);
	// if (v.getValidateCode().equals(user.getUserValidateCode())) {
	// User updateUser = new User();
	// updateUser.setUserAccount(user.getUserAccount());
	// updateUser.setUserPassword(Md5Util.md5Encode(user.getUserPassword()));
	// resetResult = userService.resetUserPassword(updateUser);
	// } else {
	// resultObj.put("code", -3);
	// resultObj.put("message", "验证码输入错误！");
	// return resultObj.toString();
	// }
	// } else {
	// resultObj.put("code", -2);
	// resultObj.put("message", "验证码输入错误或已失效！");
	// return resultObj.toString();
	// }
	//
	// if (resetResult == 1) {
	// // 密码重置成功后删除验证码记录
	// Validate deleteValidate = new Validate();
	// deleteValidate.setValidatePhone(user.getUserAccount());
	// deleteValidate.setValidateCode(user.getUserValidateCode());
	// validateService.deleteValidate(deleteValidate);
	// resultObj.put("code", 0);
	// resultObj.put("url", request.getContextPath() + "/user/toLogin");
	// } else {
	// resultObj.put("code", -1);
	// resultObj.put("message", "密码重设失败！");
	// }
	// return resultObj.toString();
	// }

	@RequestMapping("/infoModify")
	public ModelAndView userInfoModify(HttpServletRequest request) {
		Map<String, Object> attrMap = new HashMap<String, Object>();
		User loginUser = this.getSessionUser(request);
		List<User> userList = userService.findUserById(loginUser.getUserId());
		if (userList.size() == 1) {
			attrMap.put("user", userList.get(0));
			return this.packModeAndView(request, "/user/infoModify", null, attrMap);
		} else {
			return this.packModeAndView(request, "/book/error", "用户不存在！", attrMap);
		}

	}

	@RequestMapping("/infoModifySave")
	public ModelAndView userInfoModifySave(User user, HttpServletRequest request) {
		User loginUser = this.getSessionUser(request);
		user.setUserId(loginUser.getUserId());
		int updateResult = userService.updateUserInfo(user);
		if (updateResult == 1) {
			return this.packModeAndView(request, "redirect:/user/info", null, null);
		} else {
			return this.packModeAndView(request, "/book/error", "用户资料修改失败！", null);
		}

	}
}
